import Vue from 'vue'
import mallstore from '@/applications/mall/store'
import shopstore from '@/applications/shop/store'
import {
  logintype_byurl,
  getLoginType
} from '@/utils/auth'
const whiteList = ['deliver', "refund", "delete", "audit"]
/**权限指令**/
const has = Vue.directive('has', {
  inserted: function(el, binding, vnode) {
    // 获取页面按钮权限
    let type = logintype_byurl()
    let btnPermissionsArr = '';
    if (binding.value) {
      if ((binding.value == 'refund' || binding.value == 'send') && type == 'shop'&&el.parentNode) {
        el.parentNode.removeChild(el)
        return false
      }
      if (whiteList.indexOf(binding.value) > -1) {
        btnPermissionsArr = vnode.context.$route.meta.id;
        if (!Vue.prototype.$_has(btnPermissionsArr, binding.value)&&el.parentNode) {
          el.parentNode.removeChild(el);
        }
      } else {
        if (type == 'saas') {
          var store = saasstore
        } else if (type == 'mall') {
          var store = mallstore
        } else if (type == 'shop') {
          var store = shopstore
        }
        // 如果指令传值，获取指令参数，判断插件权限
        let addons = store.state.common.addons
        if (binding.value != -1 && addons && addons.indexOf(binding.value) == -1&&el.parentNode) {
          el.parentNode.removeChild(el);
        }
      }
    } else {
      // 否则获取路由中的参数，根据路由的btnPermissionsArr和当前登录人按钮权限做比较。
      btnPermissionsArr = vnode.context.$route.meta.id;
      if (!Vue.prototype.$_has(btnPermissionsArr, "update")&&el.parentNode) {
        el.parentNode.removeChild(el);
      }
    }
  }
});
// 权限检查方法
Vue.prototype.$_has = function(value, value_type) {
  let isExist = false;
  let login_type = getLoginType()
  if (login_type == 'mall' || login_type == 'saas' || login_type == 'shop') {
    // 获取用户按钮权限、
    let type = login_type + '_ruleList'
    let btnPermissionsStr = JSON.parse(localStorage.getItem(type));
    if (btnPermissionsStr == undefined || btnPermissionsStr == null) {
      return false;
    }
    if (btnPermissionsStr.findIndex(_ => _.level == value && _.resource == value_type) > -1) {
      isExist = true;
    }
  } else {
    isExist = true;
  }
  return isExist;
};
export {
  has
}
